import { forwardRef, ReactElement, useImperativeHandle, useState } from 'react'
import { Modal } from 'antd'

export const commonModalStyle = {
  width: '50vw'
}

export type CommonModalProps = {
  children: ReactElement
  onOk: () => Promise<boolean> | boolean | void
  onCancel: () => void
  title: string
  onOpen?: () => void
  footer?: ReactElement | null
}

const CommonModal = forwardRef(({ children, onOk, onCancel, title, onOpen, footer }: CommonModalProps, ref) => {
  const [open, setOpen] = useState(false)

  const showModal = () => {
    setOpen(true)
    onOpen?.()
  }
  const handleOk = () => {
    const doneOk = onOk()

    if (doneOk instanceof Promise) {
      doneOk.then((isOk) => {
        if (isOk) {
          setOpen(false)
        }
      })
    } else if (typeof doneOk === 'boolean') {
      if (doneOk) {
        setOpen(false)
      }
    } else {
      setOpen(false)
    }
  }

  const handleCancel = () => {
    setOpen(false)
    onCancel()
  }

  useImperativeHandle(ref, () => ({
    showModal
  }))

  return (
    <Modal {...commonModalStyle} open={open} title={title} onCancel={handleCancel} onOk={handleOk} footer={footer}>
      {children}
    </Modal>
  )
})

export default CommonModal
